import { createRouter, createWebHashHistory } from 'vue-router'
import Index_new from '@/views/Index_new.vue'
const subModules = import.meta.glob('@/views/**/*.vue')
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
      {
      path: '/', //斜杠默认跳转到index
      redirect: '/login',
      },
      {
      path: '/index',
      name: 'index',
      component: Index_new
      },
    {
      path: '/login',
      name: 'login',
      component: ()=>import("@/views/Login.vue"),
    },
      {
      path: '/:catchAll(.*)',
      name: 'NotFound',
      component: ()=>import("@/views/404.vue"),
      },
  ]
})

function getChildrenRoute(menusTemp){
    let children = []
      menusTemp.forEach(m => {
        let temp =  m.children.map(c => {
           return {
             path: m.path+c.path,
             name: c.viewName,
             component:subModules["../views"+m.path+"/"+c.viewName+".vue"]
            }
         })
        children.push(...temp)
      })
      return children
}

router.addMyRoute = function(menus) {
    const menusTemp = menus||JSON.parse(sessionStorage.getItem("menus"));
      if(!menusTemp){
        router.push("/login")
        return
  }

      let children =  getChildrenRoute(menusTemp)
      let myRoute =  {
        path: '/index',
        name: 'index',
        component: Index_new,
        children:[
            {
            path: '/main',
            name: 'main',
            component: ()=>import("@/views/Main.vue")
        },
            {
            path: '/currHomePage',
            name: 'currHomePage',
            component: ()=>import("@/views/CurrHomePage.vue")
        },
          {
            path: '/:catchAll(.*)',
            name: 'NotFound',
            component: ()=>import("@/views/404.vue"),
          },
        ]
      }
      myRoute.children.push(...children)
      router.addRoute(myRoute)
}

router.addMyRoute()
//
router.beforeEach((to, from, next)=>{
  let routes = router.getRoutes();
  if("/login" == to.path || to.path.indexOf("/client") > -1 ){
      next()
  }else{
      let item = sessionStorage.getItem("user");
      if(item){
          next()
      }else{//没有user
          router.push("/clientHome")
      }
  }
})

export default router
